package ttelectronic.mobileholder.service;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import ttelectronic.mobileholder.common.MHCommon;
import android.bluetooth.BluetoothSocket;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class MHSMSService extends Thread {
	private OutputStream mOutStream;
	private Context mContext;
	private Handler mHandler;
	private int mState;

	public MHSMSService(Context context, BluetoothSocket socket, Handler handler) {
		mContext = context;
		mHandler = handler;
		mState = 0;
		try {
			mOutStream = socket.getOutputStream();
		} catch (IOException e) {
			Log.e(MHCommon.TAG, "SMS ERROR: Temp sockets not created", e);
		}
	}

	public void run() {
		super.run();
		while (true) {
			ContentResolver contentResolver = mContext.getContentResolver();
			Uri uriSMSURI = Uri.parse("content://sms/inbox");
			Cursor cursr = contentResolver.query(uriSMSURI, null, "read = 0",
					null, null);
			cursr.moveToFirst();
			int unread = cursr.getCount();
			PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(
					mOutStream));
			if (unread == 0) {
				if (mState == 1) {
					Log.d(MHCommon.TAG + " SMS : ", "No message unread");
					pWriter.write(MHCommon.POSTMSG_NO_SMS);
					pWriter.flush();
					mState = 0;
				}
			} else {
				Log.d(MHCommon.TAG + " SMS : ", unread + " message(s) unread!");
				pWriter.write(MHCommon.POSTMSG_HAD_SMS);
				pWriter.flush();
				mState = 1;
			}

			Message msg = mHandler.obtainMessage(MHCommon.MESSAGE_SMS);
			Bundle bundle = new Bundle();
			bundle.putString(MHCommon.BUNDLE_SMS, unread + "");
			msg.setData(bundle);
			mHandler.sendMessage(msg);
			cursr.close();
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
